import React from 'react';
import { Calendar } from 'antd';
import Immutable from 'immutable';
import { formatDate, _str2Int } from '../../util/common';
import { WeaErrorPage, WeaTools, WeaScroll } from 'ecCom';
global.currentMonth = formatDate(new Date(), "yyyy-MM");
//日历日程元素
class CalendarTemplate extends React.Component {
	constructor(props) {
        super(props);
		//刷新url或点击门户或刷新日历日程元素重置currentSelectDate为系统当前日期
		currentSelectDate = formatDate(new Date(), "yyyy-MM-dd");
        this.state = {
            data: props.data,
        }
    }
	onPanelChange(value, mode) {
		const { eid, hpid, subCompanyId } = this.props;
		$("#calendar_content" + eid).html("");
        if ("month" === mode) {
            var selectdate = "";
            if (typeof value === 'object') {
                var year = value.getYear();
                var month = value.getMonth() + 1 < 10 ? '0' + (value.getMonth() + 1) : value.getMonth() + 1;
                currentMonth = year + '-' + month;
                selectdate = year + '-' + month + '-01';
                if (selectdate === (formatDate(new Date(), "yyyy-MM") + "-01")) {
                    currentSelectDate = formatDate(new Date(), "yyyy-MM-dd");
                } else {
                    currentSelectDate = selectdate;
                }
            } else {
                selectdate = value;
                currentSelectDate = selectdate;
            }
            //this.loadEvents(eid,this.state.data);
            const params = {
                ebaseid: 'MyCalendar',
                eid: eid,
                hpid,
                subCompanyId,
                selectdate,
            }
            WeaTools.callApi('/api/portal/element/mycalendar', 'POST', params).then(result=> {
	            ls.set('edata-'+eid, result);
	            this.setState({
	                data: result.data,
	                refresh: false,
	            });
	            this.loadEvents(eid,data.data);
	        });
        }
	}
	loadEvents(eid, caldata){
		const eventsObj = caldata.dateevents;
        for (var k in eventsObj) {
            if (k === currentSelectDate) {
                const currEvents = eventsObj[k];
                const htmlArr = new Array;
                const size = currEvents.length;
                const height = size * 34;
                htmlArr.push("<div id='planDataEvent' class='planDataEvent' style='height:"+(height+1)+"px;overflow-y: hidden; outline: none;'><div id='planDataEventchd' style='height:"+height+"px;'>");
                const calevents = caldata.events;
                for (var i = 0; i < size; i++) {
                    const eventKey = currEvents[i];
                    const eventsArr = calevents[eventKey];
                    htmlArr.push("<div class='hand dataEvent' height='34px' onclick='clickData(" + eventKey + "," + eid + ")' title="+eventsArr[2]+">");
                    htmlArr.push("<div class='dataEvent1' style='background:#a32929;'></div>");
                    htmlArr.push("<div class='dataEvent2'><div class='dataEvent2_1'>"+eventsArr[4]+"&nbsp;&nbsp;"+eventsArr[5]+"</div></div>");
                    htmlArr.push("<div class='dataEvent3'>"+eventsArr[2]+"</div>");
                    htmlArr.push("</div>");
                }
                htmlArr.push("</div></div>");
                $("#calendar_content" + eid).html(htmlArr.join(''));
            }
        }
	}
	componentDidMount() {
		const { eid, data } = this.props;
		$("#calendar_" + eid + " .ant-fullcalendar-cell").attr("onclick", "clickCalendarDay(this,'" + eid + "')");
		this.loadEvents(eid, data);
		window.getMyCalendarDatas = this.onPanelChange.bind(this);
	}
	render() {
		const { eid, userid, data } = this.props;
		let caldata = data;
		$("#calendar_" + eid).find(".ant-fullcalendar-current").removeClass("ant-fullcalendar-current");
		$("#calendar_" + eid).find(".ant-fullcalendar-event").removeClass("ant-fullcalendar-event");
		return <div id={`calendar_${eid}`}>
				<Calendar fullscreen={false} onPanelChange={this.onPanelChange.bind(this)} value={new Date(currentSelectDate)} dateCellRender={dateCellRender.bind(this,eid,caldata)}/>
				<WeaScroll typeClass="scrollbar-macosx" conHeightNum={0}>
					<div id={`calendar_content${eid}`} style={{maxHeight:'103px'}}></div>
				</WeaScroll>
				<div style={{textAlign:'center'}}><input className="addWorkPlan" type="button" onClick={doAdd.bind(this,userid,eid)} title="添加"/>
				</div>
			</div>
	}
}

class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return (
			<WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
		);
	}
}
CalendarTemplate = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(CalendarTemplate);
export default CalendarTemplate;



/** --------- 通用js函数 -----------**/

window.currentSelectDate = formatDate(new Date(), "yyyy-MM-dd");
function dateCellRender(eid, data, value){
    var dataStr1 = formatDate(new Date(value.time), 'yyyy-M-d');
    var dateStr = formatDate(new Date(value.time), 'yyyy-MM-dd');
    var dateevents = data.dateevents;
    var events = data.events;
    var isRender = false;
    for (var dateKey in dateevents) {
        if (dateKey === dateStr) {
            var attrs = {
                size: dateevents[dateKey].length
            };
            var html = dateevents[dateKey].map(function(dKey, v){
                var dData = events[dKey];
                attrs['event' + v] = dData[0] + "-split-" + dData[2] + "-split-" + dData[4] + "-split-" + dData[5];
            });
            $("#calendar_" + eid + " .ant-fullcalendar-cell[title='" + dataStr1 + "'] .ant-fullcalendar-value").attr(attrs).addClass("ant-fullcalendar-event");
            isRender = true; 
        }
    }
    if(dateStr===currentSelectDate){
        $("#calendar_" + eid + " .ant-fullcalendar-cell[title='" + dataStr1 + "'] .ant-fullcalendar-value").addClass("ant-fullcalendar-current");
    }
    if(!isRender){//没有时候去掉所有的event
        var curObj = $("#calendar_" + eid + " .ant-fullcalendar-cell[title='" + dataStr1 + "'] .ant-fullcalendar-value")
        if(curObj.attr("size")){
            var size = eval(curObj.attr("size"))
            for(var i =0;i<size;i++){
                curObj.removeAttr("event"+i)
            }
            curObj.removeAttr("size")
        }
    }
}

function doAdd(userid,eid){
    var calendarDialog = new Dialog();
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var selectDate = year + "-" + (month > 9 ? month : "0" + month) + "-" + (day > 9 ? day : "0" + day);
    if (currentSelectDate != '') {
        selectDate = currentSelectDate;
    }
    var beginTime = (hours > 9 ? hours : "0" + hours) + ":" + (minutes > 9 ? minutes : "0" + minutes);
    var url = '/workplan/data/WorkPlanEdit.jsp?from=1&selectUser='+userid+'&planName=&beginDate=' + selectDate + '&beginTime=' + beginTime + '&endDate=' + selectDate + '&endTime=';
    //openFullWindowHaveBar(url);

    if (window.top.Dialog) {
        calendarDialog = new window.top.Dialog();
    } else {
        calendarDialog = new Dialog();
    };
    calendarDialog.URL = url;
    calendarDialog.Width = 600;
    calendarDialog.Height = 600;
    calendarDialog.checkDataChange = false;
    calendarDialog.Title = "日程";
    calendarDialog.callbackfunc4CloseBtn=function(){
        window.getMyCalendarDatas(currentSelectDate,"month",eid);
    }
    var hasRfdh = true;
    calendarDialog.show();
}

var refreshCalendar = function(eid){
    $("#toolbar_"+eid+" [name=refreshbtn] img").trigger('click')
    setTimeout(function(){
        if($("#calendar_"+eid+" .ant-fullcalendar-current")){
            $("#calendar_"+eid+" .ant-fullcalendar-current").trigger('click')
        }
    },100)
}

/** --------- 日历日程js函数 -----------**/
window.clickCalendarDay = function(obj,eid){
    $("#calendar_"+eid).find(".ant-fullcalendar-current").removeClass("ant-fullcalendar-current");
    var title = $(obj).attr("title");
    var ndate = "";
    var currentMonthStr =  "";
    if(title) {
        var titlearr =  title.split("-");
        ndate = titlearr[0];
        currentMonthStr = titlearr[0];
        if(parseInt(titlearr[1]) < 10){
            ndate = ndate + "-0" + titlearr[1];
            currentMonthStr = currentMonthStr + "-0"+titlearr[1];
        }else{
            ndate = ndate + "-" + titlearr[1];
            currentMonthStr = currentMonthStr + "-"+titlearr[1];
        }
        if(parseInt(titlearr[2]) < 10){
            ndate = ndate + "-0" + titlearr[2];
        }else{
            ndate = ndate + "-" + titlearr[2];
        }
        
    }
    if(ndate){
        currentSelectDate = ndate;
    }
    //判断点击的是否为当前显示月份，否的话刷新新月份的日历日程，并默认选中所点击的日期
    if(currentMonthStr !== currentMonth){
        currentMonth = currentMonthStr;
        window.getMyCalendarDatas(currentSelectDate,"month",eid);
    }
    var dom = $(obj).find(".ant-fullcalendar-event");
    var size = _str2Int($(dom).attr("size"),0);
    var htmlArr = new Array;
    var height = size * 34;
    htmlArr.push("<div id='planDataEvent' class='planDataEvent' style='height:"+(height+1)+"px; overflow-y: hidden; outline: none;'><div id='planDataEventchd' style='height:"+height+"px;'>");
    for (var i = 0; i < size; i++) {
        var event = $(dom).attr("event"+i);
        if(!_isEmpty(event)){
            var arr = event.split("-split-");
            htmlArr.push("<div class='hand dataEvent' height='34px' onclick='clickData(" + arr[0] + "," + eid + ")' title="+arr[1]+">");
            htmlArr.push("<div class='dataEvent1' style='background:#a32929;'></div>");
            htmlArr.push("<div class='dataEvent2'><div class='dataEvent2_1'>"+arr[2]+"&nbsp;&nbsp;"+arr[3]+"</div></div>");
            htmlArr.push("<div class='dataEvent3'>"+arr[1]+"</div>");
            htmlArr.push("</div>");
        }
    }
    htmlArr.push("</div></div>");
    $("#calendar_content"+eid).html(htmlArr.join(''));
}

//点击数据
var clickData = function(id,eid){
    var url = '/workplan/data/WorkPlanDetail.jsp?from=1&workid=' + id;
    //openFullWindowHaveBar(url);
    var calendarDialog = new Dialog();
    if (window.top.Dialog) {
        calendarDialog = new window.top.Dialog();
    } else {
        calendarDialog = new Dialog();
    };
    var hasRfdh = true;
    calendarDialog.URL = url;
    calendarDialog.Width = 600;
    calendarDialog.Height = 600;
    calendarDialog.checkDataChange = false;
    calendarDialog.Title = "日程";
    calendarDialog.callbackfunc4CloseBtn=function(){
        window.getMyCalendarDatas(currentSelectDate,"month",eid);
    }
    calendarDialog.show();
}

/** --------- 日历日程js函数 -----------**/